package com.haitaoit.chengquan.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.hardware.Camera;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.github.retrofitutil.BuildConfig;
import com.github.retrofitutil.NetWorkManager;
import com.haitaoit.chengquan.business.http.OKHttp;
import com.haitaoit.chengquan.utils.FileFinal;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.socialize.PlatformConfig;

import java.util.Stack;

import cn.jpush.android.api.JPushInterface;


/**
 * ExitApplication
 * <p/>
 * 刘霄鹏
 * <p/>
 * 2015年9月28日 下午2:46:04
 *
 * @version 1.0.0
 */
public class ExitApplication extends Application {
    public static ExitApplication instance;
    public static Stack<Activity> activityStack;
    public static final String baseUrl = "http://cqapi.hai-tao.net/";
    public static double latitude, longitude;
    private       String  JPushId;
    public static Context context;

    private RefWatcher sRefWatcher;

    public ExitApplication() {
    }
    @Override
    public void onCreate() {
        super.onCreate();
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        context = this;
        SDKInitializer.initialize(this);

        this.instance = this;
        FileFinal.createAppDirectory();
        PlatformConfig.setWeixin("wx97e8a7d5fce75c70", "af49b4ef80fb8b818388af98fc439334");
        PlatformConfig.setSinaWeibo("221130913", "898a6e996fd3457cfdf0ba4782d3a482");
        PlatformConfig.setQQZone("1105935142", "RV2Bhh4dTo7L8QDY");
        setImagment();
        Logger.addLogAdapter(new AndroidLogAdapter());

        OKHttp.init(getApplicationContext());// BuildConfig.DEBUG
        NetWorkManager.getInstance(this, baseUrl, BuildConfig.DEBUG).complete();


        //关闭闪光灯
        try{

            Camera m_Camera;
            m_Camera = Camera.open();
            Camera.Parameters mParameters;
            mParameters = m_Camera.getParameters();
            mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            m_Camera.setParameters(mParameters);
            m_Camera.release();
        } catch(Exception ex){}

        //放开这段代码就可以直接进行内存泄漏的检测
//        sRefWatcher = LeakCanary.install(this);

////      也是异常工具类
//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());

        //异常工具类
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaghtHandler());




    }
    public static RefWatcher getRefWatcher(Context context) {
        ExitApplication application = (ExitApplication) context.getApplicationContext();
        return application.sRefWatcher;
    }

    public String getJPushId() {
        if (JPushId == null) {
            JPushId = JPushInterface.getRegistrationID(this);
        }
        Log.i("======", "=====JPushId=" + JPushId);
        return JPushId;
    }

    /**
     * 异常处理
     */
    public class MyUncaghtHandler implements Thread.UncaughtExceptionHandler{

        @Override
        public void uncaughtException(Thread t, Throwable e) {

            //出现错误保证不能出现xxx报错信息，直接闪退
            System.exit(0);
           // Process.killProcess(Process.myPid());

        }
    }


    /**
     * 设置image-loader的属性
     */
    public void setImagment() {
        // 初始化ImageLoader
        @SuppressWarnings("deprecation")
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                //				.showStubImage(R.drawable.ic_stub) // 设置图片下载期间显示的图片
                //				.showImageForEmptyUri(R.drawable.ic_empty) // 设置图片Uri为空或是错误的时候显示的图片
                //				.showImageOnFail(R.drawable.ic_empty) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(50)) // 设置成圆角图片
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();

        ImageLoader.getInstance().init(config);
    }

    // 单例模式中获取唯一的MyApplication实例
    public synchronized static ExitApplication getInstance() {
        if (null == instance) {
//            instance = new ExitApplication();
            instance = new ExitApplication();

        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        if (activity != null) {
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * 登陆状态 。默认为 false为未登陆
     */
    public static boolean session_enter = false;

    /**
     * 设置登陆状态，true 为登陆，false 为未登陆 setSession(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 –
     * 可选)
     *
     * @param session void
     * @throws
     * @since 1.0.0
     */
    public static void setSession(boolean session) {
        session_enter = session;
    }

    /**
     * 获取登陆状态，true 为登陆 false 为未登陆 getSession(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 –
     * 可选)
     *
     * @return boolean
     * @throws
     * @since 1.0.0
     */
    public static boolean getSession() {
        return session_enter;
    }

    /**
     * 用户id
     */
    public static String user_id = "";

    /**
     * 设置用户id getUser_id(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static void setUser_id(String User_id) {
        user_id = User_id;
    }

    /**
     * 用户id getUser_id(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static String getUser_id() {
        return user_id;
    }

    /**
     * 用户id
     */
    public static String Loaction = "";

    /**
     * 设置地址
     *
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static void setLoaction(String loaction) {
        Loaction = loaction;
    }

    /**
     * 地址
     *
     * @return String
     * @throws
     * @since 1.0.0
     */
    public static String getLoaction() {
        return Loaction;
    }

    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
